<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb">
      <el-col :span="6">
        时间：
        <el-date-picker clearable size="small" style="width: 200px" @change="getList" v-model="date" type="date"
          value-format="yyyy-MM-dd" placeholder="时间">
        </el-date-picker>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="handlerefresh">刷新</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="6">
        <div class="oneday theday" @click="handleClick">
          <img src="@/assets/image/foot.png">
          <el-button type="primary" size="mini" class="editstyle">上传本周食谱</el-button>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="oneday theday">
          <el-image style="width: 100px; height: 100px" :src="imageListUrl"/>
        </div>
      </el-col>
      <el-col :span="6" v-for="(item, index) in dataList" :key="index" class="contentlist">
        <div :class="'oneday theday' + index" v-for="(key, val) in item">
          <div class="topinfor">
            <p class="weekword">{{ week[index] }}<span data-v-7b513308="" :class="'yuanback yuanback' + index"></span>
            </p>
            <p>{{ transform(val) }}</p>
          </div>
          <div class="bottominfor">
            <div class="threeMeal" v-for="(info, i) in item[val]" :key="i">
              <!-- <div class="Breakfast">
                <p><i class="el-icon-fork-spoon"></i>{{info.mealTypeName}}</p>
                <p class="footName" v-for="(fitem,findex) in info.foodNames" :key="findex">{{fitem}}</p>
              </div>
              <div class="Breafastimg" >
                <div v-if="info.filePath">
                  <el-image v-for="(item,index) in info.filePath.split(',')" :key="item" :src="item" style="width:40px;height:40px" :preview-src-list="[item]"></el-image>
                </div>
                <div  v-for="(ingredientsGroup, i) in info.cuineFood" :key="i">
                  <div class="ingredient" v-for="(ingredient, index) in ingredientsGroup" :key="ingredient.id">
                    <span class="ing-name">{{ ingredient.name }}</span>
                    <span class="ing-weight">{{ingredient.phr}}g</span>
                  </div>
                </div>
              </div> -->

              <div class="Breakfast">
                <p><i class="el-icon-fork-spoon"></i>{{ info.mealTypeName }}</p>
                <div v-for="(fitem, findex) in info.foodNames" :key="findex">
                  <p class="footName">{{ fitem }}</p>
                  <div class="Breafastimg">
                    <div class="breakfast-images" v-if="info.filePath">
                      <el-image v-if="findex < info.filePath.split(',').length" :key="`${findex}-image`"
                        :src="info.filePath.split(',')[findex]" style='width:40px;height:40px' fit='cover'
                        :preview-src-list="[[info.filePath.split(',')[findex]]]"></el-image>
                      <!-- <el-image v-for="(item, index) in info.filePath.split(',')" :key='item' :src='item' style='width:40px;height:40px' fit='cover' :preview-src-list='[item]'></el-image> -->
                    </div>
                    <div style="width: 100%;" v-if="info.cuineFood[findex] && Array.isArray(info.cuineFood[findex])">
                      <div class="ingredient" v-for="(ingredient, index) in info.cuineFood[findex]"
                        :key="ingredient.id">
                        <span class="ing-name">{{ ingredient.name }}</span>
                        <!-- 如果重量字段为 phr -->
                        <span class="ing-weight">{{ ingredient.phr }}g</span>
                        <!-- 如果重量字段不是 phr，请替换为实际字段名 -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <el-button type="primary" icon="el-icon-edit" circle class="editstyle"
            @click="handleUpdate(item, val)"></el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改菜谱对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学期" prop="date">
          <el-date-picker clearable size="small" style="width: 200px" v-model="form.date" type="date"
            value-format="yyyy-MM-dd" placeholder="时间" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item v-for="(item, index) in form.MealFoods" :key="index" :label="item.mealTypeName">
          <el-row>
            <el-col :span="10">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd(index)">新增{{ item.mealTypeName
                }}</el-button>
              <el-form-item label-width="0" label="" :prop="'MealFoods.' + index + '.foodNames'"
                style="margin-bottom: 0;">
                <div class="block select-menu" v-for="(infor, ii) in item.foodNames">
                  <el-cascader filterable v-model="item.foodNames[ii]" :options="foodoptions"
                    :props="{ expandTrigger: 'hover' }" @change="handleChange($event, item)"></el-cascader>
                  <i v-show="ii !== 0" class="el-icon-circle-close" style="margin-left: 6px;cursor: pointer;"
                    @click="handleDel(index, ii)"></i>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label-width="0" label="" :prop="'MealFoods.' + index + '.filePath'"
                style="margin-bottom: 0;">
                <imageUpload v-model="item.filePath" :limit="4" class="addimg" />
              </el-form-item>
            </el-col>
            <el-table :data="item.cuisineFoodList" border>
              <el-table-column label="菜谱名称" prop="foodName" align="center" />
              <el-table-column label="食材名称" prop="name" align="center" />
              <el-table-column label="用量（g/ml）" prop="phr" align="center" />
            </el-table>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="增加每周食谱" :visible.sync="open1" width="800px" append-to-body ref="upload">
      <el-upload class="avatar-uploader" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" ref="upload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { addfoodrecipe, listCookbook, listfood, listfoodoptions, getSelectImage, selectCuisineFood, add, addlist } from '@/api/base/grow'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from "@/utils/auth";

export default {
  name: "gzt",
  dicts: ['food_type'],
  data() {
    return {
      week: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      dataList: [],
      date: new Date,
      form: {
        MealFoods: [
          {
            foodNames: []
          }
        ]
      },
      rules: {},
      title: '修改菜谱',
      open: false,
      foodoptions: [],
      selectFoodName: '',
      open1: false,
      imageUrl: '',
      imageListUrl: '',
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },

    };
  },
  created() {
    // this.getList();
    this.getList()
    //食材选择
    this.getfoodoptions()
  },
  mounted() {
    this.addlist()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.weedUrl = res
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    submitForm1() {
      var data = {
        "menuImageUrl": this.weedUrl.
          url,
        "menuName": this.weedUrl.fileName
        ,
      }
      console.log(data)
      add(data).then(res => {
        if(res.code==200){
          this.$message.success('添加成功')
          this.open1=false
          this.$refs.upload.clearFiles()
          this.addlist()
        }
       
      })

    },
    addlist(){
      addlist().then(res=>{
        this.imageListUrl=res.rows[0].menuImageUrl
      })
    },
    cancel1(){
      this.open1=false
    },
    /**食材下拉*/
    async getfoodoptions() {
      try {
        const { data } = await listfoodoptions()
        // 构建选项数组
        this.foodoptions = Object.keys(data).map(item => {
          const children = data[item].map(food => ({
            label: food.foodName,
            value: food.foodName
          }))
          return {
            label: item,
            value: item,
            children: children
          }
        })
      } catch (e) {
        console.log(e)
      }
    },
    handleChange(selectedOptions, item) {
      if (selectedOptions.length > 1) {
        this.selectFoodName = selectedOptions[selectedOptions.length - 1];
        this.getImage().then(imagePath => {
          item.filePath = item.filePath ? item.filePath + ',' + imagePath : imagePath;
        });
        this.getCuisineFood(item)
      }
    },
    async getImage() {
      let params = {
        foodName: this.selectFoodName
      }
      const res = await getSelectImage(params);
      if (res.code === 200) {
        return res.msg
      }
    },
    async getCuisineFood(item) {
      let params = {
        foodName: this.selectFoodName
      }
      const res = await selectCuisineFood(params);
      if (res.code === 200) {

        res.data.forEach(i => {
          i.foodName = this.selectFoodName
        });
        await this.$nextTick(() => {
          if (item.cuisineFoodList && item.cuisineFoodList.length) {
            item.cuisineFoodList = item.cuisineFoodList.concat(res.data)
          } else {
            item.cuisineFoodList = res.data
          }
          console.log('item.cuisineFoodList', item.cuisineFoodList);

        }); // 等待DOM更新
        this.$forceUpdate()
      }
    },
    /**数据处理*/
    transform(val) {
      let date = val.split(" "),
        year = date[0];
      year = year.substring(year.indexOf("-") + 1, year.lenght);
      return year
    },

    /** 查询一周时间列表食谱 */
    async getList() {
      try {
        this.loading = true;
        let params = {
          date: parseTime(this.date, '{y}-{m}-{d}')
        }
        const data = await listCookbook(params);
        this.dataList = data;
        // this.total = data.total;
        this.loading = false;
      } catch (e) {
        console.log(e)
      }
    },
    /**刷新*/
    handlerefresh() {
      this.data = parseTime(new Date, '{y}-{m}-{d}')
      this.getList()
    },
    /**新增*/
    handleAdd(index) {
      let obj = {}
      if (!this.form.MealFoods[index].foodNames) {
        this.form.MealFoods[index].foodNames = []
      }
      this.form.MealFoods[index].foodNames.push(obj)
      console.log('this.form.MealFoods', this.form.MealFoods);
    },
    // 删除
    handleDel(index, ii) {
      this.form.MealFoods[index].foodNames.splice(ii, 1)
      let imagesArray = this.form.MealFoods[index].filePath.split(',');
      imagesArray.splice(ii, 1); // 删除指定索引的元素
      // 将处理过的数组转换回字符串
      this.form.MealFoods[index].filePath = imagesArray.join(',');
    },
    /**编辑**/
    handleUpdate(row, val) {
      // this.form.MealFoods=JSON.parse(JSON.stringify(row[val]));
      // this.form.date=val
      // this.form.MealFoods=this.form.MealFoods.map(item=>{
      //   if(item.foodNames){
      //     item.foodNames=item.foodNames.map(infor=>{
      //       if(infor.indexOf(",")!=-1){
      //         infor=infor.split(",")
      //         infor=infor.map(res=>{
      //           return res
      //         })
      //       }
      //       return infor
      //     })
      //   }else{
      //     item.foodNames=[[]]
      //   }

      this.form.MealFoods = JSON.parse(JSON.stringify(row[val]));
      this.form.date = val;

      this.form.MealFoods.forEach((meal) => {
        if (!meal.foodNames) {
          meal.foodNames = [[]];
        } else {
          meal.foodNames = meal.foodNames.map((foodNamesStr) => {
            return foodNamesStr.split(',').map((name) => name.trim());
          });
        }

        // 创建一个新的 cuisineFoods 数组，其中 foodName 为合并后的字符串
        if (meal.cuineFood) {
          const cuisineFoods = meal.cuineFood.flatMap((cuisineFoodsGroup, index) => {
            const foodName = meal.foodNames[index].join('，');
            return cuisineFoodsGroup.map((foodItem) => ({
              ...foodItem,
              foodName,
            }));
          });
          // 添加新数组到 meal 中，例如：meal.transformedCuisineFoods
          meal.cuisineFoodList = cuisineFoods;
        }
        return meal;
      });

      console.log(this.form.MealFoods);
      this.open = true;
    },
    // 表单重置
    reset() {
      this.form = {
        MealFoods: [
          {
            FoodNames: null,
            FilePath: null,
            id: null,
          }
        ]

      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          for (let i = 0; i < this.form.MealFoods.length; i++) {
            if (this.form.MealFoods[i].foodNames) {
              this.form.MealFoods[i].foodNames = this.form.MealFoods[i].foodNames.map(item => {
                item = item.toString()
                console.log(item)
                return item
              })
            }
          }
          console.log(this.form)
          let obj = {}
          obj[this.form.date] = this.form.MealFoods
          // debugger
          // console.log(obj)
          addfoodrecipe(obj).then(res => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          })

          this.open = false;
        }
      })
    },
    handleClick() {
      this.open1 = true
    },
  }
};
</script>

<style lang="scss" scoped>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: solid 1px #ccc;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

.mb8 {
  display: flex;
  flex-wrap: wrap;

  p {
    margin: 0;
  }

  .el-col-6 {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    /* -webkit-box-pack: center; */
    -ms-flex-pack: center;
    justify-content: center;
  }

  .oneday {
    width: 100%;
    background: #f3fff9;
    margin-top: 10px;
    margin-bottom: 10px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-pack: start;
    -ms-flex-pack: start;
    justify-content: flex-start;
    position: relative;
    padding: 10px 15px;

    .topinfor {
      margin-bottom: 15px;
      text-align: center;

      &>p {
        margin: 0;
      }

      .weekword {
        position: relative;
        z-index: 5;
        line-height: 31px;
        margin-bottom: 7px;

        .yuanback {
          width: 70px;
          height: 16px !important;
          background: #87cd9b;
          border-radius: 8px;
          display: block;
          position: absolute;
          left: 50%;
          margin-left: -35px;
          margin-top: -15px;
          z-index: -1;
        }

        .yuanback0,
        .yuanback5,
        .yuanback6 {
          background: #87cd9b;
        }

        .yuanback1 {
          background-color: #6a8ed6;
        }

        .yuanback2 {
          background-color: #f7e279;
        }

        .yuanback3 {
          background-color: #ff9e9e;
        }

        .yuanback4 {
          background-color: #81e2ea;
        }

      }
    }

    .bottominfor {
      line-height: 28px;

      i {
        color: #ff9e9e;
        margin-right: 10px;
      }

      .footName {
        font-size: 14px;
        color: #9d7653;
        line-height: 20px;
      }

      .el-image {
        margin-right: 10px;
        height: auto !important;
        max-height: 40px;
      }
    }

    .Breafastimg {
      display: flex;
      padding: 10px;

      .breakfast-images {
        width: 50px;
        height: 50px;
      }

      .ingredient {
        display: flex;
        justify-content: space-between;
        width: 100%;

        .ing-weight {
          color: #797979;
          font-size: 12px;
        }

        .ing-name {
          font-size: 12px;
          color: #666;
        }
      }
    }

    .editstyle {
      position: absolute;
      right: 11px;
      padding: 3px;
      border-radius: 0;
      background: #ff6f61;
      border: none;
      z-index: 6;
    }
  }

  .theday1 {
    background: #f3f7ff;
  }

  .theday2 {
    background: #fffdf3;
  }

  .theday3 {
    background: #fff3f3;
  }

  .theday4 {
    background: #f2feff;
  }
}

.addimg {
  margin-left: 10px;

  ::v-deep &>div {
    display: flex;
    flex-wrap: wrap;

    .el-upload-list__item {
      width: 68px;
      height: 68px;
      margin-bottom: 0;
    }

    .el-upload--picture-card {
      width: 68px;
      height: 68px;
      line-height: 68px;
      margin-bottom: 0;
    }
  }

  ::v-deep .el-upload__tip {
    display: none;
  }
}

.select-menu {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.select-menu:first-child {
  margin-right: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>
